<template>
  <div class="derOnlyOneContainer _containers resourceTools">
    <!-- 
      :style="{
            transformOrigin: 'top left',
            left: `${left}px`,
            top: `${top}px`,
          }"
    -->
    <!-- 菜单禁止拖动 滚动逻辑未处理 -->
    <Title title="授课资源" :allowMove="false" @close="close" @getPosition="getPosition" />
    <div class="contentBox">
      <iframe :src="uri" frameborder="0"></iframe>
    </div>
  </div>
</template>

<script>
import { mapState } from 'pinia';
import closeIcon from '../../../assets/teaching/close.svg';
import Title from '../panel/title.vue';
import useMenu from '../../../store/menu';
import { getStorage, updateStorage } from '../../../utils/tools';

export default {
  components: { Title },
  data() {
    return {
      left: 0,
      top: 0,
      status: false,
      closeIcon,
      uri: '',
    };
  },
  computed: {
    ...mapState(useMenu, ['inType', 'courseData']),
  },
  watch: {
    inType: {
      handler(newVal) {
        // 进入时 获取资源
        if (newVal == 'resource') {
          console.log('手动获取资源');
          window.electronAPI.getResource();
        }
      },
      immediate: true,
    },
    // 资源更新 更新
    courseData: {
      handler() {
        console.log('更新资源列表');
        this.setUri();
      },
      immediate: true,
    },
  },
  created() {
    const that = this;
    window.addEventListener('message', function (event) {
      console.log('event.data:', event.data); // 输出: value1
      console.log('event.origin =====> ', event.origin);
      // 1. 检查消息来源是否可信
      // check() {}
      // 2.处理接收到的数据,发送给主窗口
      // event.data
      const { id: currentId } = event.data;
      updateStorage('resourceList', {
        currentId,
      });
      if (window.electronAPI) {
        // 将选中的资源传递给窗口mainWindows
        window.electronAPI.resourceChange(event.data);
        // 3. 选择后关闭弹窗
        that.$emit('close');
      }
    });
  },

  methods: {
    // Title 组件返回的 x, y值
    getPosition({ x, y }) {
      this.left = x;
      this.top = y;
    },
    close() {
      this.startPage = false;
      this.$emit('close');
    },
    setUri() {
      const resourceList = getStorage('resourceList');
      // 参数中存在 # 所以需要转义
      let uri = `${import.meta.env.VITE_IFRAME_URI_PREFIX}#/clientResource`;
      if (resourceList) {
        uri = `${uri}?data=${encodeURIComponent(resourceList)}`;
      }
      this.uri = uri;
    },
  },
};
</script>
<style lang="scss" scoped>
._containers {
  width: 20em;
  height: 36.25em;
  background: #fff;
  box-shadow: 0px 0px 16px 0px rgb(0 0 0 / 20%);
  position: relative;
  box-sizing: border-box;
  border-radius: 0.875em;
  border-radius: 8px;
  display: flex;
  flex-direction: column;

  .contentBox {
    flex: 1;
    display: flex;

    iframe {
      height: 100%;
      width: 100%;
    }
  }
}
</style>

<style lang="scss">
.resourceTools {
  border-radius: 8px;

  .title {
    padding: 13px 20px;
  }
}
</style>
